
package gradle.common.redis.utils;

import gradle.common.core.context.SpringApplicationContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.redisson.api.RLock;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RedissonClient;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * RedissonUtil
 */
@Slf4j
public class RedissonUtil {

    /**
     * 获取锁
     */
    public static RLock getLock(String lockKey) {
        RedissonClient redissonClient = SpringApplicationContext.getBeanIfNull(RedissonClient.class);
        return redissonClient.getLock(lockKey);
    }

    /**
     * get rate limiter instance
     *
     * @param limiterName 限流器名称，唯一
     * @return {@link RRateLimiter}
     */
    public static RRateLimiter getRateLimiter(String limiterName) {
        RedissonClient redissonClient = SpringApplicationContext.getBeanIfNull(RedissonClient.class);
        Assert.hasText(limiterName, "name of rate limiter cannot blank");
        return redissonClient.getRateLimiter(limiterName);
    }

    /**
     * 加锁操作
     *
     * @return boolean
     */

    public static boolean tryLock(String lockName, long waitTime, long leaseTime) {
        RedissonClient redissonClient = SpringApplicationContext.getBeanIfNull(RedissonClient.class);
        boolean getLock = false;
        try {
            RLock rLock = getLock(lockName);
            log.info("【RedissonUtil】试图获取锁，lockKey:{}，threadName:{}, 是否为当前线程：{}", lockName, Thread.currentThread().getName(), rLock.isHeldByCurrentThread());
            getLock = rLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            log.info("【RedissonUtil】获取结果{}，lockKey:{}，threadName:{}, 是否为当前线程：{}", getLock, lockName, Thread.currentThread().getName(), rLock.isHeldByCurrentThread());
            if (getLock) {
                log.info("【RedissonUtil】获取锁成功,lockName={}", lockName);
            } else {
                log.info("【RedissonUtil】获取锁失败,lockName={}", lockName);
            }
        } catch (Exception e) {
            log.error("【RedissonUtil】获取式锁异常，lockName={}, 异常信息：{}", lockName, ExceptionUtils.getStackTrace(e));
            getLock = false;
        }
        return getLock;
    }


    /**
     * 加锁操作
     *
     * @return boolean
     */
    public static Boolean tryLockTimeOut(String lockName, long waitTime, long leaseTime) {
        Boolean getLock = false;
        try {
            // Thread thread = Thread.currentThread();
            // log.info("【RedissonUtil】试图获取锁，Key:{}，threadId: {} threadName:{}, 是否为当前线程：{}", lockName, thread.getId(), thread.getName(), rLock.isHeldByCurrentThread());
            getLock = getLock(lockName).tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            // log.info("【RedissonUtil】获取结果{}，Key:{}，threadId: {} threadName:{}, 是否为当前线程：{}", getLock, lockName, thread.getId(), thread.getName(), rLock.isHeldByCurrentThread());
            // if (getLock) {
            //     log.info("【RedissonUtil】获取锁成功,lockName={}", lockName);
            // } else {
            //     log.info("【RedissonUtil】获取锁失败,lockName={}", lockName);
            // }
        } catch (Exception e) {
            log.error("【RedissonUtil】获取式锁异常，lockName={}, 异常信息：{}", lockName, ExceptionUtils.getStackTrace(e));
            getLock = null;
        }
        return getLock;
    }

    /**
     * 加锁操作
     *
     * @return RLock RLock
     */
    public static RLock tryLockTimeOut(long waitTime, long leaseTime, String lockName) {
        try {
            RLock rLock = getLock(lockName);
            Thread thread = Thread.currentThread();
            log.info("【RedissonUtil】试图获取锁，Key:{}，threadId: {} threadName:{}, 是否为当前线程：{}", lockName, thread.getId(), thread.getName(), rLock.isHeldByCurrentThread());
            boolean getLock = rLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            log.info("【RedissonUtil】获取结果{}，Key:{}，threadId: {} threadName:{}, 是否为当前线程：{}", getLock, lockName, thread.getId(), thread.getName(), rLock.isHeldByCurrentThread());
            if (getLock) {
                log.info("【RedissonUtil】获取锁成功,lockName={}", lockName);
            } else {
                log.info("【RedissonUtil】获取锁失败,lockName={}", lockName);
            }
            return rLock;
        } catch (Exception e) {
            log.error("【RedissonUtil】获取式锁异常，lockName={}, 异常信息：{}", lockName, ExceptionUtils.getStackTrace(e));
            return null;
        }
    }


    /**
     * 锁lockKey
     *
     * @param lockName  锁Key
     * @param leaseTime 使用定义的leaseTime获取锁。必要时等待，直到锁可用。锁将在定义的leaseTime间隔后自动释放。
     * @return 基于Redis的Lock实现实现了可重入锁。
     */
    public static RLock lock(String lockName, long leaseTime) {
        try {
            RLock lock = getLock(lockName);
            log.info("【RedissonUtil】获取锁，lockKey:{}，threadName:{}, 是否为当前线程：{}", lockName, Thread.currentThread().getName(), lock.isHeldByCurrentThread());
            lock.lock(leaseTime, TimeUnit.SECONDS);
            log.info("【RedissonUtil】获取到锁，lockKey:{}，threadName:{}, 是否为当前线程：{}", lockName, Thread.currentThread().getName(), lock.isHeldByCurrentThread());
            return lock;
        } catch (Exception e) {
            log.error("【RedissonUtil】获取锁时异常，{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }


    /**
     * 解锁
     *
     * @param lockName 锁名称
     */
    public static void unlock(String lockName) {
        RedissonClient redissonClient = SpringApplicationContext.getBeanIfNull(RedissonClient.class);

        try {
            RLock lock = redissonClient.getLock(lockName);
            if (lock != null && lock.isHeldByCurrentThread()) {
                // log.info("【RedissonUtil】手动释放锁，lockKey:{}，threadName:{}, 是否为当前线程：{}", lockName, Thread.currentThread().getName(), lock.isHeldByCurrentThread());
                lock.unlock();
                // log.info("【RedissonUtil】手动释放锁完成，lockKey:{}，threadName:{}, 是否为当前线程：{}", lockName, Thread.currentThread().getName(), lock.isHeldByCurrentThread());
            }
        } catch (Exception e) {
            log.error("【RedissonUtil】解锁时异常，{}", ExceptionUtils.getStackTrace(e));
        }
    }


    /**
     * 销毁方法
     */
    void shutdown() {
        RedissonClient redissonClient = SpringApplicationContext.getBeanIfNull(RedissonClient.class);
        if (redissonClient != null) {
            redissonClient.shutdown();
        }
    }

}
